<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2019/1/16
 * Time: 10:30
 */
namespace app\shop\controller;
use think\Controller;
use think\File;
use think\Request;
use think\Db;
use Qcloud\Cos\Client;
require_once "../extend/tencent/vendor/autoload.php";
class Upload extends Base
{

    /**
     * upload 上传图片
     *
     */
    public function upload(){
        $configconfig = [
            'region' => config('tengx')['region'],
            'schema' => config('tengx')['schema'], //协议头部，默认为http
            'credentials'=> array(
                'secretId'  => config('tengx')['secretId'] ,
                'secretKey' => config('tengx')['secretKey']
            )
        ];
        $cosClient = new Client($configconfig);
        //-----------------------------------
        $size = $_FILES['file']['size'];
        $oldname = $_FILES['file']['name'];
        //-----------------------------------
        $filePath = $_FILES['file']['tmp_name'];
        $type = explode(".",$_FILES['file']['name']);
        $type = end($type);
        //组装图片名
        $key = md5(time().uuid()).'.'.$type;
        try {
            $result = $cosClient->putObject(array(
                'Bucket' => config('tengx')['Bucket'], //格式：BucketName-APPID
                'Key' => $key,
                'Body' => fopen($filePath, 'rb'),
            ));
            // 请求成功
            echo config('tengx')['domain'] . $key . '?size=' . $size . '&oldname=' . $oldname;
        } catch (\Exception $e) {
            // 请求失败
            echo($e);
        }
    }

    public function xiazaiFf($pathname,$imgpath){
        $zip_path = ROOT_PATH . 'public' . DS . 'uploads/zip';
        if (!file_exists($zip_path)) {
            mkdir($zip_path);
        }
        $zipname = $zip_path . '/' . $pathname . '.zip';
        $zip = new \ZipArchive();
        $zip->open($zipname, \ZipArchive::CREATE);
        $this->addFileToZip($imgpath, $zip); //调用方法，对要打包的根目录进行操作，并将ZipArchive的对象传递给方法
        $zip->close(); //关闭处理的zip文件
//        //这里是下载zip文件
        header("Content-Type: application/zip");
        header("Content-Transfer-Encoding: Binary");
        header("Content-Length: " . filesize($zipname));
        header("Content-Disposition: attachment; filename=\"" . basename($zipname) . "\"");
        readfile($zipname);
        unlink($zipname);
        $this->deldir($imgpath);
        @unlink($imgpath);
        exit;
    }
    public function mulu($keyarray,$localPath){
        $configconfig = [
            'region' => config('tengx')['region'],
            'schema' => config('tengx')['schema'], //协议头部，默认为http
            'credentials'=> array(
                'secretId'  => config('tengx')['secretId'] ,
                'secretKey' => config('tengx')['secretKey']
            )
        ];
        $cosClient = new Client($configconfig);
        try {
            $bucket = config('tengx')['Bucket']; //存储桶，格式：BucketName-APPID
//            $key = "d14e3f3d60b29d11f4047e0250f46793.jpg"; //对象在存储桶中的位置，即称对象键
//            $localPath = "D:\phpStudy\WWW/fuma\public/1.jpg";//下载到本地指定路径
            $key = str_replace(config('tengx')['domain'],'',$keyarray['uy_url']);
            $type = explode(".",$key);
            $type = end($type);
            $uy_name = explode(".",$keyarray['uy_name']);
            $cosClient->getObject(array(
                'Bucket' => $bucket,
                'Key' => $key,
                'SaveAs' => $localPath . '/' . $uy_name[0] . '.' . $type));
        } catch (\Exception $e) {
//            // 请求失败
//            echo "$e\n";
        }
    }
    public function addFileToZip($path,$zip){
        $handler=opendir($path); //打开当前文件夹由$path指定。
        while(($filename=readdir($handler))!==false){
            if($filename != "." && $filename != ".."){//文件夹文件名字为'.'和‘..’，不要对他们进行操作
                if(is_dir($path."/".$filename)){// 如果读取的某个对象是文件夹，则递归
                    $this->addFileToZip($path."/".$filename, $zip);
                }else{ //将文件加入zip对象
                    $zip->addFile($path . "/" . $filename);
//                    $zip->addFile($path."/".$filename,basename($path."/".$filename));
                }
            }
        }
        @closedir($path);
    }
    public function deldir($dir)
    {
        $dh = opendir($dir);
        while ($file = readdir($dh)) {
            if ($file != "." && $file != "..") {
                $fullpath = $dir . '/' . $file;
                if (!is_dir($fullpath)) {
                    unlink($fullpath);
                } else {
                    $this->deldir($fullpath);
                }
            }
        }
        closedir($dh);
        if (rmdir($dir)) {
            return true;
        } else {
            return false;
        }
    }
}